﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SimpleBlog.Infrastructure.Repositories;
using SimpleBlog.ViewModels;
using SimpleBlog.Helpers;
using SimpleBlog.Models;
using System.Linq.Expressions;
using System.Net;

namespace SimpleBlog.Controllers
{
    public class TagController : Controller
    {
        ITagRepository _tagRepository;
        IPostRepository _postRepository;

        public TagController(ITagRepository tagRepository, IPostRepository postRepository)
        {
            _tagRepository = tagRepository;
            _postRepository = postRepository;
        }

        public ActionResult Index(string name, int page = 1, int count = 5)
        {
            if (name == null)
                throw new HttpException(404, "You have to indicate a Tag name.");
            if (page < 1 || count < 1)
                throw new HttpException((int)HttpStatusCode.BadRequest, "Page or Count parameter has to be greater than 1.");

            var tag = _tagRepository.GetByEncodedName(name);

            if (tag == null)
                throw new HttpException(404, string.Format("The Tag \"{0}\" doesn't exists.", name));

            Expression<Func<Post, bool>> tagFilter = x => x.Tags.Any(y => y.TagId == tag.TagId);

            var posts = _postRepository.Search(tagFilter, page, count);
            var postsCount = _postRepository.Count(tagFilter);

            if (postsCount == 0)
                Server.LogException(new Exception("There are a tag without any post in DB"));

            var maxPage = Math.Max((int)Math.Ceiling((double)postsCount / count), 1);
            TagViewModel model = new TagViewModel()
            {
                PostList = new PostListViewModel()
                {
                    MaxPage = maxPage,
                    Page = page,
                    Items = posts.Select(x => new PostViewModel() { PostItem = x, Summary = true })
                },
                TagName = tag.Name
            };

            return View(model);
        }

        public PartialViewResult Cloud()
        {
            var steps = 6;
            var items = _tagRepository.GetAllAndCount();
            bool tagsExists = items.Count > 0;
            double max = tagsExists ? items.Values.Max() : 0;
            double min = tagsExists ? items.Values.Min() : 0;

            var model = new TagCloudViewModel()
            {
                Items = items,
                Steps = steps,
                Rate = count => Math.Min((int)((steps) * ((count - min) / (max - min)) + 1), steps)
            };

            return PartialView(model);
        }
    }
}
